# 每日构建SDK  https://ci.openharmony.cn/workbench/cicd/dailybuild/dailylist
SDK_URL="https://cidownload.openharmony.cn/version/Master_Version/OpenHarmony_5.1.0.63/20250507_021256/version-Master_Version-OpenHarmony_5.1.0.63-20250507_021256-ohos-sdk-public.tar.gz"

# 打印系统版本信息
echo "打印操作系统版本信息："
cat /etc/os-release

echo "$ id -un"
id -un

# 检查ohos_react_native目录是否预热成功
echo "检查 ohos_react_native 目录是否预热成功"
echo "$ ls -al"
ls -al
echo "$ ls -al ./third_party/"
ls -al ./third_party/

echo "$ rm -rf ~/.hvigor/"
rm -rf ~/.hvigor/

PRJ_DIR=$(pwd)/third_party/ohos_react_native
WORK_DIR=$(pwd)/RN_Work

# 检查 WORK_DIR 目录
echo "$ mkdir -p "$WORK_DIR""
mkdir -p "$WORK_DIR"
echo "$ ls -al $WORK_DIR/"
ls -al "$WORK_DIR/"

TOOLS_DIR="$WORK_DIR/command-line-tools"
PREBUILD_DIR="$WORK_DIR/rnoh_prebuild"

# 准备SDK
function prepare_sdk() {
	echo "准备 SDK"
	echo "$ cd $WORK_DIR"
	cd "$WORK_DIR"

	#  mkdir -p "$TOOLS_DIR"/
	echo "$ rm -rf OHOS_SDK* && mkdir -p OHOS_SDK/sdk/ && cd OHOS_SDK"
	rm -rf OHOS_SDK* && mkdir -p OHOS_SDK/sdk/ && cd OHOS_SDK

	echo "$ git clone https://gitee.com/jarayard/command-line-tools_sdk-01234.git --depth 1"
	git clone https://gitee.com/jarayard/command-line-tools_sdk-01234.git --depth 1
	if [ $? -ne 0 ]; then
		echo "[Warning]: 下载失败，重试!!!"
		echo "$ rm -rf "$WORK_DIR"/command-line-tools_sdk-01234/"
		rm -rf "$WORK_DIR"/command-line-tools_sdk-01234/
		echo "$ git clone https://gitee.com/jarayard/command-line-tools_sdk-01234.git --depth 1"
		git clone https://gitee.com/jarayard/command-line-tools_sdk-01234.git --depth 1
		if [ $? -ne 0 ]; then
			echo "[Error]: 下载失败!!!"
			return 1
		fi
	fi

	echo "$ cp ./command-line-tools_sdk-01234/sdk_part_00* ./sdk/"
	cp ./command-line-tools_sdk-01234/sdk_part_00* ./sdk/

	echo "$ git clone https://gitee.com/jarayard/command-line-tools_sdk-567.git --depth 1"
	git clone https://gitee.com/jarayard/command-line-tools_sdk-567.git --depth 1
	if [ $? -ne 0 ]; then
		echo "[Warning]: 下载失败，重试!!!"
		echo "$ rm -rf $WORK_DIR/command-line-tools_sdk-567/"
		rm -rf "$WORK_DIR/command-line-tools_sdk-567/"
		echo "$ git clone https://gitee.com/jarayard/command-line-tools_sdk-567.git --depth 1"
		git clone https://gitee.com/jarayard/command-line-tools_sdk-567.git --depth 1
		if [ $? -ne 0 ]; then
			echo "[Error]: 下载失败!!!"
			return 1
		fi
	fi

	echo "[Success]: 下载完成!!!"
	echo "$ cp ./command-line-tools_sdk-567/sdk_part_00* ./sdk/"
	cp ./command-line-tools_sdk-567/sdk_part_00* ./sdk/

	echo "开始解压 SDK"
	echo "$ cd sdk"
	cd sdk
	echo "$ cat sdk_part_00* > sdk.tar.xz"
	cat sdk_part_00* >sdk.tar.xz

	echo "$ tar -xJf sdk.tar.xz"
	tar -xJf sdk.tar.xz
	if [ $? -ne 0 ]; then
		echo "[Error]: 解压失败!!!"
		return 1
	fi
	echo "[Success]: 解压完成!!!"

	echo "$ ls ./sdk/default/"
	ls ./sdk/default/

	echo "$ mv ./sdk/ $TOOLS_DIR/"
	mv ./sdk/ "$TOOLS_DIR/"

	# ===================================================================================================================

	echo "开始下载每日构建 SDK"
	echo "$ curl -sS -f -L -- $SDK_URL > sdk_openharmony.tar.gz"
	curl -f -L -- "$SDK_URL" >sdk_openharmony.tar.gz
	if [ $? -ne 0 ]; then
		echo "[Error]: 下载失败!!!"
		return 1
	fi
	echo "[Success]: 下载完成!!!"

	echo "开始校验 SDK"
	local correct_SHA256="fa4deaba2813104d791d903637e9d4487c5c2e0898e04f7e1205eb9121480b01"
	local sdk_sum=$(sha256sum sdk_openharmony.tar.gz)
	sdk_sum=${sdk_sum:0:64} # SHA-256 产生64个字符的哈希值
	if [ "x$sdk_sum" != "x$correct_SHA256" ]; then
		echo "tools_sum(no x) is : x$sdk_sum"
		echo "SHA-256_command-line-tools(no x) is : x$correct_SHA256"
		echo "Error: please change sdk_openharmony.tar.gz!!!"
		return 1
	fi
	echo "[Success]: SDK 校验正确!!!"

	echo "开始解压每日构建 SDK"
	echo "$ tar -zxvf ./sdk_openharmony.tar.gz"
	tar -zxvf ./sdk_openharmony.tar.gz
	echo "$ cd ./linux"
	cd ./linux
	if [ $? -ne 0 ]; then
		echo "[Error]: 未找到 linux 目录!!!"
		return 1
	fi

	echo "$ for file in ls ./"
	for file in $(ls ./); do
		echo "$ unzip -qo $file"
		unzip -qo "$file"
		if [ $? -ne 0 ]; then
			echo "[Error]: $file 解压失败!!!"
			return 1
		fi
		echo "$ rm -f $file"
		rm -f "$file"
		echo "[Success]: $file 解压完成!!!"
	done
	echo "[Success]: 每日构建 SDK 解压完成!!!"

	echo "$ mkdir -p $TOOLS_DIR/sdk/default/openharmony/"
	mkdir -p "$TOOLS_DIR/sdk/default/openharmony/"
	echo "$ mv ./ets/ ./js/ ./native/ ./previewer/ ./toolchains/ $TOOLS_DIR/sdk/default/openharmony/"
	mv ./ets/ ./js/ ./native/ ./previewer/ ./toolchains/ "$TOOLS_DIR/sdk/default/openharmony/"

	# ===================================================================================================================

	echo "[Success]: SDK 准备完成!!!"

	echo "$ rm -rf $WORK_DIR/OHOS_SDK*"
	rm -rf "$WORK_DIR/OHOS_SDK*"
	return 0
}

# 准备command-line-tools
function prepare_tools() {
	# 本地调试时，在此直接return 0，手动解压command-line-tools到RN_Work
	# return 0

	# 检查command-line-tools文件夹是否存在
	if [ -d "$TOOLS_DIR" ]; then
		# 获取文件夹大小（以字节为单位）
		FOLDER_SIZE=$(du -sb "$TOOLS_DIR" | cut -f1)

		# 检查是否大于1G
		if [ "$FOLDER_SIZE" -gt 1073741824 ]; then
			echo "文件夹 '$TOOLS_DIR' 存在，且大小大于 1GB。提前结束prepare_tools()函数。"
			return 0
		else
			echo "文件夹 '$TOOLS_DIR' 存在，但大小不超过 1GB。"
		fi
	else
		echo "文件夹 '$TOOLS_DIR' 不存在。"
	fi

	echo "start prepare command-line-tools"

	rm -rf "$TOOLS_DIR"/

	mv "$PREBUILD_DIR"/command-line-tools/ "$WORK_DIR"/

	cd "$TOOLS_DIR"/
	for file in $(ls ./*.tar.xz); do
		tar -xJf "$file"
		if [ $? -ne 0 -a $? -ne 1 ]; then
			echo "Failed to extract file $file!!!"
			return 1
		fi
		echo "Unzipped $file successfully!!!"
		rm -f "$file"
	done

	echo "The command-line-tools is ready, except for the sdk"

	# ===================================================================================================================

	prepare_sdk
	if [ $? -ne 0 ]; then
		echo "Failed to extract prepare_sdk()!!!"
		return 1
	fi

	echo "The command-line-tools is ready, including the sdk"

	return 0
}

function prepare_config_files() {
	echo "start prepare config_files"

	cp "$PREBUILD_DIR"/config_files/npm/.npmrc /root/
	if [ $? -ne 0 ]; then
		echo "Failed to copy npmrc!!!"
		return 1
	fi
	
	cp "$PREBUILD_DIR"/config_files/npm/.npmrc ~/
	if [ $? -ne 0 ]; then
		echo "Failed to copy npmrc!!!"
		return 1
	fi

	rm -rf ~/.ohpm/ && mkdir ~/.ohpm/
	cp "$PREBUILD_DIR"/config_files/ohpm/.ohpmrc ~/.ohpm/
	if [ $? -ne 0 ]; then
		echo "Failed to copy .ohpmrc!!!"
		return 1
	fi
	echo ".npmrc and .ohpmrc already exists"

	# sleep 3  # 暂停3秒，用于调试

	return 0
}

function prepare_project() {
	echo "start prepare project"

	cd "$PRJ_DIR"
	if [ $? -ne 0 ]; then
		echo "Error: Cannot find ohos_react_native!!!"
		return 1
	fi
	echo "The ohos_react_native path already exists"

	# pull latest code
	git fetch
	echo "$ git branch -a"
	git branch -a
	git config --global user.email "rnohci@example.com"
	git config --global user.name "RNOH CI"
	# git add *
	# git commit -m "local changes"
	if [ "$manifest_file" = "ohos_react_native_packages.xml" ]; then
		# release 分支
		echo "$ git rebase remotes/gitcode/0.72.5-ohos-5.0-release"
		git rebase remotes/gitcode/0.72.5-ohos-5.0-release
	else
		# master 分支 manifest_file=ohos_react_native_master.xml
		echo "$ git rebase remotes/gitcode/master"
		git rebase remotes/gitcode/master
	fi
	if [ $? -ne 0 ]; then
		echo "rebase failed!!!"
		return 1
	fi
	git log -10 --pretty=format:"%h - %s"
	git status
	git diff

	cd ./tester/harmony
	if [ $? -ne 0 ]; then
		echo "Error: Cannot find harmony project!!!"
		return 1
	fi
	echo "The harmony project path already exists"

	cp build-profile.template.json5 build-profile.json5

	#
	#  下载hvigor插件和生成local.properties文件的事，hvigor会自己处理，不用手动下载
	#

	# sleep 3  # 暂停3秒，用于调试

	return 0
}

function prepare_third_party() {
	echo "start prepare third_party"

	cd "$PRJ_DIR"/tester/harmony/react_native_openharmony/src/main/cpp/third-party
	if [ $? -ne 0 ]; then
		echo "Cannot find the third-party of ohos_react_native!!!"
		# sleep 3  # 暂停3秒，用于调试
		rm -rf "$PRJ_DIR"/
	fi
	echo "The third-party of ohos_react_native already exists"

	cp "$PREBUILD_DIR"/third_party/third-party.tar.xz ./
	if [ $? -ne 0 ]; then
		echo "Failed to copy third-party!!!"
		rm -f third-party.tar.xz
		return 1
	fi
	echo "copy third-party.tar.xz successfully"

	tar -xJf third-party.tar.xz
	if [ $? -ne 0 ]; then
		echo "Failed to extract third-party.tar.xz!!!"
		return 1
	fi
	echo "Unzipped third-party.tar.xz successfully!!!"

	rm -f third-party.tar.xz

	# sleep 3  # 暂停3秒，用于调试

	return 0
}

function prepare_react_native_core() {
	echo "start prepare react-native-core"

	cd "$PRJ_DIR"/packages

	# make boost folder not a submodule, just a normal folder
	git rm react-native-core
	mkdir react-native-core

	cp "$PREBUILD_DIR"/react-native-core/react-native-core.tar.xz ./
	if [ $? -ne 0 ]; then
		echo "Failed to copy react-native-core!!!"
		rm -f react-native-core.tar.xz
		return 1
	fi
	echo "copy react-native-core.tar.xz successfully"

	tar -xJf react-native-core.tar.xz
	if [ $? -ne 0 ]; then
		echo "Failed to extract react-native-core.tar.xz!!!"
		return 1
	fi
	echo "Unzipped react-native-core.tar.xz successfully!!!"

	rm -f react-native-core.tar.xz

	return 0
}

function prepare_boost() {
	echo "start prepare boost"

	cd "$PRJ_DIR"/packages/tester/harmony/react_native_openharmony/src/main/cpp/third-party

	# make boost folder not a submodule, just a normal folder
	git rm boost
	mkdir boost

	cp "$PREBUILD_DIR"/boost/boost.tar.xz ./
	if [ $? -ne 0 ]; then
		echo "Failed to copy boost!!!"
		rm -f boost.tar.xz
		return 1
	fi
	echo "copy boost.tar.xz successfully"

	tar -xJf boost.tar.xz
	if [ $? -ne 0 ]; then
		echo "Failed to extract boost.tar.xz!!!"
		return 1
	fi
	echo "Unzipped boost.tar.xz successfully!!!"

	rm -f boost.tar.xz
	echo "$ ls ./boost"
	ls ./boost

	return 0
}

function switch_submodules_to_mirror() {
	cd $PRJ_DIR

	sed -i 's|https://github.com/fmtlib/fmt.git|https://gitcode.com/gh_mirrors/fm/fmt.git|g' .gitmodules
	sed -i 's|https://github.com/facebook/folly.git|https://gitcode.com/gh_mirrors/fol/folly.git|g' .gitmodules
	sed -i 's|https://github.com/google/double-conversion.git|https://gitcode.com/gh_mirrors/dou/double-conversion.git|g' .gitmodules
	sed -i 's|https://github.com/google/glog.git|https://gitcode.com/gh_mirrors/glog6/glog.git|g' .gitmodules
	sed -i 's|https://github.com/libevent/libevent.git|https://gitcode.com/gh_mirrors/li/libevent.git|g' .gitmodules
	sed -i 's|https://github.com/fastfloat/fast_float.git|https://gitcode.com/gh_mirrors/fa/fast_float.git|g' .gitmodules
	sed -i 's|https://github.com/facebook/hermes.git|https://gitcode.com/gh_mirrors/hermes/hermes.git|g' .gitmodules
	sed -i 's|https://github.com/facebook/react-native|https://gitcode.com/gh_mirrors/re/react-native|g' .gitmodules
	sed -i 's/ts-node \.\/scripts\/verify-docs\.ts/ls/g' package.json

	# don't print submodule upgrade progress. Progress bar would result in lots of lines
	sed -i 's|git submodule update --init --recursive --progress|git submodule update --init --recursive|g' package.json

	cat package.json
}

function prepare() {
	cd "$WORK_DIR"
	if [ $? -ne 0 ]; then
		echo "$WORK_DIR 不存在!!!"
		return 1
	fi

	echo "start prepare build"

	if [ -d rnoh_prebuild ]; then
		echo "Start to sync rnoh_prebuild ########"
		cd rnoh_prebuild
		git fetch origin
		git reset --hard origin/master
		cd ..
	else
		echo "Start to clone rnoh_prebuild ########"
		git clone https://gitee.com/jarayard/rnoh_prebuild.git --depth 1
		if [ $? -ne 0 ]; then
			echo "Warning: git clone rnoh_prebuild failed! Start retry!!!"
			rm -rf "$PREBUILD_DIR"/
			git clone https://gitee.com/jarayard/rnoh_prebuild.git --depth 1
			if [ $? -ne 0 ]; then
				rm -rf "$PREBUILD_DIR"/
				echo "Error: git clone rnoh_prebuild failed!!!"
				return 1
			fi
		fi
	fi
	echo "The rnoh_prebuild path already exists"

	# if [ $? -ne 0 ]; then
	#     echo "Node版本错误!!!"
	#     return 1
	# fi
	# echo "Node版本正确!!!"
	# return 1
	# 测试

	# ===================================================================================================================
	# ===================================================================================================================
	prepare_tools
	if [ $? -ne 0 ]; then
		rm -rf "$TOOLS_DIR"/
		echo "Failed to execute prepare_tools()!!!"
		return 1
	fi
	# 测试，看有没有GLIBC版本报错
	export PATH="$TOOLS_DIR"/bin:"$TOOLS_DIR"/tool/node/bin:$PATH
	echo "开始检测Node版本!!!"
	echo "环境变量：$PATH"
	echo "$ node -v"
	node -v
	echo "$ npm -v"
	npm -v
	echo "$ npm config ls -l"
	npm config ls -l

	# ===================================================================================================================
	prepare_project
	if [ $? -ne 0 ]; then
		echo "Failed to execute prepare_project()!!!"
		return 1
	fi
	# ===================================================================================================================
	prepare_third_party
	if [ $? -ne 0 ]; then
		echo "Failed to execute prepare_third_party()!!!"
		return 1
	fi
	# ===================================================================================================================
	prepare_config_files
	if [ $? -ne 0 ]; then
		echo "Failed to execute prepare_config_files()!!!"
		return 1
	fi

	# ===================================================================================================================
	# ===================================================================================================================

	echo "prepare build successfully!!!"

	return 0
}

function prepare_77() {
	cd "$WORK_DIR"
	if [ $? -ne 0 ]; then
		echo "$WORK_DIR 不存在!!!"
		return 1
	fi

	echo "start prepare build"

	if [ -d rnoh_prebuild ]; then
		echo "Start to sync rnoh_prebuild ########"
		cd rnoh_prebuild
		git fetch origin
		git reset --hard origin/master
		cd ..
	else
		echo "Start to clone rnoh_prebuild ########"
		git clone https://gitee.com/jarayard/rnoh_prebuild.git --depth 1
		if [ $? -ne 0 ]; then
			echo "Warning: git clone rnoh_prebuild failed! Start retry!!!"
			rm -rf "$PREBUILD_DIR"/
			git clone https://gitee.com/jarayard/rnoh_prebuild.git --depth 1
			if [ $? -ne 0 ]; then
				rm -rf "$PREBUILD_DIR"/
				echo "Error: git clone rnoh_prebuild failed!!!"
				return 1
			fi
		fi
	fi
	echo "The rnoh_prebuild path already exists"

	prepare_tools
	if [ $? -ne 0 ]; then
		rm -rf "$TOOLS_DIR"/
		echo "Failed to execute prepare_tools()!!!"
		return 1
	fi
	export PATH="$TOOLS_DIR"/bin:"$TOOLS_DIR"/node-v22.14.0-linux-x64/bin:$PATH

	echo "开始检测Node版本!!!"
	echo "环境变量：$PATH"
	echo "uname -m"
	uname -m
	echo "cd $TOOLS_DIR/tool/node/bin"
	cd "$TOOLS_DIR/tool/node/bin"
	echo "ls"
	ls
	echo "$ ./node -v"
	./node -v
	echo "$ node -v"
	node -v
	echo "$ npm -v"
	npm -v
	echo "$ npm config ls -l"
	npm config ls -l
	echo "$ npm install -g pnpm@latest-10"
	npm install -g pnpm@latest-10
	echo "$ pnpm -v"
	pnpm -v

	# ===================================================================================================================
	# prepare_project
	# if [ $? -ne 0 ]; then
	#     echo "Failed to execute prepare_project()!!!"
	#     return 1
	# fi
	# ===================================================================================================================

	# pull latest code
	cd $PRJ_DIR
	git fetch
	git branch -a
	git config --global user.email "rnohci@example.com"
	git config --global user.name "RNOH CI"
	# git add *
	# git commit -m "local changes"
	git rebase remotes/gitcode/0.77.1-rc.1-ohos
	if [ $? -ne 0 ]; then
		echo "rebase failed!!!"
		return 1
	fi
	git log -10 --pretty=format:"%h - %s"
	git status
	git diff

	prepare_react_native_core
	if [ $? -ne 0 ]; then
		echo "Failed to execute prepare_react_native_core()!!!"
		return 1
	fi
	prepare_boost
	if [ $? -ne 0 ]; then
		echo "Failed to execute prepare_boost()!!!"
		return 1
	fi

	switch_submodules_to_mirror
	# ===================================================================================================================
	prepare_config_files
	if [ $? -ne 0 ]; then
		echo "Failed to execute prepare_config_files()!!!"
		return 1
	fi

	# ===================================================================================================================
	# ===================================================================================================================

	echo "prepare build successfully!!!"

	return 0
}

echo "set info"
set

if [ "$manifest_file" = "ohos_react_native_77.xml" ]; then
	echo "Access control is being executed on the branch 0.77.1-rc.1-ohos ..."
	prepare_77 $@
else
	echo "正在执行master/release分支上的门禁..."
	prepare $@
fi
exit $?
